package com.jinlia.show.modules.base.wxapp.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.modules.base.model.po.DeliveryOrderPO;
import com.jinlia.show.modules.base.wxapp.entity.UserAddress;
import com.jinlia.show.modules.base.wxapp.mapper.UserAddressMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserAddressMapperService extends ServiceImpl<UserAddressMapper, UserAddress> {

    final UserMapperService userMapperService;
    @Value("${ten-xun.map.geocoder-v1-url}")
    public String geocoderV1Url;
    @Value("${ten-xun.map.key}")
    public String tenXunMapKey;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 微信导入地址
     *
     * @param userAddress
     */
    public UserAddress importUserAddress(UserAddress userAddress) {
        String[] detailInfo = userAddress.getAddress().split(" ");
        if (detailInfo.length > 1) {
            userAddress.setAddress(detailInfo[0]);
            userAddress.setAddressName(detailInfo[1]);
        }

        //地址转换
        String url= String.format(geocoderV1Url, tenXunMapKey, userAddress.getAddress());
        ResponseEntity<JSONObject> forEntity = restTemplate.getForEntity(url, JSONObject.class);
        log.info("请求url = {},res = {}", url, forEntity.getBody());
        if (HttpStatus.OK.equals(forEntity.getStatusCode()) && "Success".equals(forEntity.getBody().getString("message"))) {
            JSONObject resultJSONObject = forEntity.getBody().getJSONObject("result");
            userAddress.setLatitude(resultJSONObject.getJSONObject("location").getDouble("lat"));
            userAddress.setLongitude(resultJSONObject.getJSONObject("location").getDouble("lng"));
        }
        //校验重复地址
        List<UserAddress> list = this.lambdaQuery()
                .eq(UserAddress::getMobile, userAddress.getMobile())
                .eq(UserAddress::getAddress, userAddress.getAddress())
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            this.lambdaUpdate()
                    .eq(UserAddress::getId, list.get(0).getId())
                    .set(UserAddress::getLastUpdateTime, LocalDateTime.now())
                    .update();
        }else {
            this.save(userAddress);
        }
        return userAddress;
    }
}
